/**
 * 比较各类互斥技术
 *
 * @author fireway
 * @since 2019年 03月 31日 星期日 09:31:43 CST
 */
package currency;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

abstract class Incrementable {
    protected long mCounter = 0;

    public abstract void increment();
}

class SynchronizingTest extends Incrementable {
    @Override
    public synchronized void increment() {
        ++mCounter;
    }
}

class LockingTest extends Incrementable {
    private Lock mLock = new ReentrantLock();

    @Override
    public void increment() {
        mLock.lock();
        try {
            ++mCounter;
        } finally {
            mLock.unlock();
        }
    }
}

public class SimpleMicroBenchmark {
    private static long test(Incrementable incr) {
        long startTime = System.nanoTime();

        for(long i = 0; i < 10000000L; i++) {
            incr.increment();
        }

        return System.nanoTime() - startTime;
    }

    public static void main(String[] args) {
        long synchTime = test(new SynchronizingTest());
        long lockTime = test(new LockingTest());
        System.out.printf("synchronized: %1$10d\n", synchTime);
        System.out.printf("Lock:         %1$10d\n", lockTime);
        System.out.printf("Lock/synchronized = %1$.3f", (double)lockTime / (double)synchTime);
    }
}
